package com.lwq.project.activemq.impl;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.TextMessage;

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import com.lwq.project.activemq.ConsumerService;

/**
 * 点对点接收消息（不接收队列里的消息存在1-1）
* @author 作者 linweiqiang
* @version 创建时间：2017年10月20日 上午10:05:24
* 类说明
*/
@Service
public class ConsumerServiceImpl implements ConsumerService {
	private Logger logger = Logger.getLogger(ConsumerServiceImpl.class);
	
	@Resource(name="jmsQueueTemplate")
    private JmsTemplate jmsQueueTemplate;
	@Resource(name="jmsTopicTemplate")
	private JmsTemplate jmsTopicTemplate;
	
	public TextMessage receiveQueue() {
		TextMessage textMessage = null;
		try {
			textMessage = (TextMessage) jmsQueueTemplate.receive();
			logger.error("从默认队列Queue收到了消息：\t"	+ textMessage.getText().toString());
		} catch (JMSException e) {
			logger.info("从默认队列Queue收到消息失败");
			e.printStackTrace();
		}
		return textMessage;
	}

	public TextMessage receiveQueue(String name) {
		if(StringUtils.isBlank(name)){
			return null;
		}
		TextMessage textMessage = null;
		Destination destination = ActiveMQQueue.createDestination(name, ActiveMQQueue.QUEUE_TYPE);
		try {
			textMessage = (TextMessage) jmsQueueTemplate.receive(destination);
			logger.error("从队列Queue" + destination+ "收到了消息：\t"	+ textMessage.getText().toString());
		} catch (Exception e) {
			logger.info("接收队列Queue消息失败：" + destination);
			e.printStackTrace();
		}
		return textMessage;
	}
	public TextMessage receiveTopic() {
		TextMessage textMessage = null;
		try {
			textMessage = (TextMessage) jmsTopicTemplate.receive();
			logger.error("从默认队列Topic收到了消息：\t"	+ textMessage.getText().toString());
		} catch (Exception e) {
			logger.info("从默认队列Topic收到消息失败");
			e.printStackTrace();
		}
		return textMessage;
	}

	public TextMessage receiveTopic(String name) {
		if(StringUtils.isBlank(name)){
			return null;
		}
		TextMessage textMessage = null;
		Destination destination = ActiveMQTopic.createDestination(name, ActiveMQTopic.TOPIC_TYPE);
		try {
			textMessage = (TextMessage) jmsTopicTemplate.receive(destination);
			logger.error("从队列Topic" + destination+ "收到了消息：\t"	+ textMessage.getText().toString());
		} catch (Exception e) {
			logger.info("接收队列Topic消息失败：" + destination);
			e.printStackTrace();
		}
		return textMessage;
	}

}
